package cn.i7baozh.sentinel.controller;

import cn.i7baozh.api.entities.CommonResult;
import cn.i7baozh.api.handler.CustomerBlockHandler;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : baoqi.zhang
 * @date :   2022/4/18 13:53
 */
@Slf4j
@RestController
public class RateLimitController {

    @SentinelResource(value = "byResource", blockHandler = "del_testHotKey")
    @GetMapping("/sentinel/flow/byResource")
    public CommonResult testHotKey(@RequestParam(required = false, value = "p1") String p1,
                                   @RequestParam(required = false, value = "p2") String p2) {
        log.info("from:{}, thread:{}", p1, p2);
        return new CommonResult(200, "成功");
    }

    public CommonResult del_testHotKey(String p1, String p2, BlockException exception) {
        return new CommonResult(300, "失败:" + exception.getClass().getCanonicalName());
    }

    /**
     * blockHandler 中的参数要保持一致才可以
     * @param p1
     * @param p2
     * @return
     */
    @GetMapping("/sentinel/flow/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler", blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handleException")
    public CommonResult customerBlockHandler(String p1, String p2) {
        int a = 10 / 0;
        return new CommonResult(200, "成功");
    }
}
